package com.ruoyi.system.websocket;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.redis.RedisCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

@ServerEndpoint(value = "/common/api/path/asset")    // WebSocket 路径
@Component
public class WebSocketServer1 {

    @Resource
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    private static Logger log = LoggerFactory.getLogger(WebSocketServer1.class);
    private static final AtomicInteger OnlineCount = new AtomicInteger(0);
    // concurrent包的线程安全Set，用来存放每个客户端对应的Session对象。
    private static CopyOnWriteArraySet<Session> SessionSet = new CopyOnWriteArraySet<Session>();


    private static RedisCache redisCache;

    private String key = "session_user:";

    @Autowired
    public void setTestService(RedisCache redisCache) {
        WebSocketServer1.redisCache = redisCache;
    }

    private Map<String, List<String>> getSessionIdList(Long userId) {
        Map<String, List<String>> redisCacheCacheList = redisCache.getCacheMap(key + userId);

        if (CollectionUtil.isEmpty(redisCacheCacheList)) {
            redisCacheCacheList = new HashMap<>();

        }
        return redisCacheCacheList;
    }

    /**
     * 连接建立成功调用的方法
     */
    private void add(Long userId, Session session) {
        Map<String, List<String>> sessin = getSessionIdList(userId);
        List<String> sessionIdList = sessin.get(userId + "");
        if (CollectionUtil.isEmpty(sessionIdList)) {
            sessionIdList = new ArrayList<>();
        }
        sessionIdList.add(session.getId());
        redisCache.setCacheMap(key + userId, sessin);
    }

    private void remove(Long userId, Session session) {
        Map<String, List<String>> sessin = getSessionIdList(userId);
        List<String> sessionIdList = sessin.get(userId + "");
        if (CollectionUtil.isEmpty(sessionIdList)) {
            return;
        }
        sessionIdList.remove(session.getId());
        redisCache.setCacheMap(key + userId, sessin);
    }

    @OnOpen
    public void onOpen(Session session) throws IOException {
        SessionSet.add(session);
        int cnt = OnlineCount.incrementAndGet(); // 在线数加1
      //  log.info("有连接加入，当前连接数为：{}", cnt);
       // System.out.println("sessionId=：{}" + session.getId());
        // SendMessage(session, "连接成功");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        SessionSet.remove(session);
        int cnt = OnlineCount.decrementAndGet();
       // log.info("有连接关闭，当前连接数为：{}", cnt);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        log.info("来自客户端的消息：{}", message);
       // System.out.println("来自客户端的消息：" + message);
        SendMessage(session, "服务器发送消息收到消息，消息内容：" + message);

    }

    /**
     * 出现错误
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
      //  log.error("发生错误：{}，Session ID： {}", error.getMessage(), session.getId());
       // error.printStackTrace();
    }

    /**
     * 发送消息，实践表明，每次浏览器刷新，session会发生变化。
     *
     * @param session
     * @param message
     */
    public static void SendMessage(Session session, String message) throws IOException {
        try {
//          session.getBasicRemote().sendText(String.format("%s (From Server，Session ID=%s)",message,session.getId()));
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            log.error("发送消息出错：{}", e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 群发消息
     *
     * @param message
     * @throws IOException
     */
    public static void BroadCastInfo(String message) throws IOException {
        for (Session session : SessionSet) {
            if (session.isOpen()) {
                SendMessage(session, message);
            }
        }
    }

    /**
     * 指定Session发送消息
     *
     * @param sessionId
     * @param message
     * @throws IOException
     */
    public static void SendMessage(String message, String sessionId) throws IOException {
        Session session = null;
        for (Session s : SessionSet) {
            if (s.getId().equals(sessionId)) {
                session = s;
                break;
            }
        }
        if (session != null) {
            SendMessage(session, message);
        } else {
            log.warn("没有找到你指定ID的会话：{}", sessionId);
        }
    }

    public void SendMessage(String message, Long userId) {

        threadPoolTaskExecutor.execute(() -> {
            Session session = null;
            for (Session s : SessionSet) {
                if (String.valueOf(userId).equals(s.getQueryString())) {
                    session = s;
                    try {
                        log.info("用户id:{},开始发送消息：{}", userId, message);
                        SendMessage(session, message);
                    } catch (IOException e) {
                        // throw new RuntimeException(e);
                        log.info("用户没有连接：{}", userId);
                    }

                }
            }
//            if (session != null) {
//                try {
//                    SendMessage(session, message);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            } else {
//                log.warn("用户没有连接：{}", userId);
//            }
        });

    }


    public void SendMessage(String message, Long userId,String type) {
        WebSocketDto webSocketDto=new WebSocketDto();
        webSocketDto.setMessage(message);
        webSocketDto.setType(type);
        threadPoolTaskExecutor.execute(() -> {
            Session session = null;
            for (Session s : SessionSet) {
                if (String.valueOf(userId).equals(s.getQueryString())) {
                    session = s;
                    try {
                        log.info("用户id:{},开始发送消息：{}", userId, message);
                        SendMessage(session, JSONUtil.toJsonStr(webSocketDto));
                    } catch (IOException e) {
                        // throw new RuntimeException(e);
                        log.info("用户没有连接：{}", userId);
                    }

                }
            }
//            if (session != null) {
//                try {
//                    SendMessage(session, message);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            } else {
//                log.warn("用户没有连接：{}", userId);
//            }
        });

    }
}